import { getToken,setToken,removeToken } from '@/utils/auth'
import { resetRouter } from '@/router/index.js'
import { usermsg } from '@/api/auth.js'

const getDefaultState = () => {
    return {
        token: getToken(),
        nickname: '',
        role: ''
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state,getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
        setToken(token)
    },
    SET_NAME: (state, nickname) => {
        state.nickname = nickname
    },
    SET_ROLE: (state, role) => {
        state.role = role
    }
}

const actions = {
    resetToken({commit}){
        return new Promise(resolve => {
            removeToken()
            commit('RESET_STATE')
            resolve()
        })
    },
    getInfo({commit,state}) {
        return new Promise(resolve => {
            usermsg({token:state.token}).then(res => {
                // console.log(res.data.data,'getInfo')
                const { role, nickname } = res.data.data
                commit('SET_ROLE', role)
                commit('SET_NAME', nickname)
                resolve(res.data.data)
            })
        })
    },
    logout({commit}){
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', '')
            resetToken()
            resetRouter()
            router.push('/login')
            resolve()
        })
    }
} 

export default {
    state,
    mutations,
    actions
}